package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupService {
    @Autowired(required = false)
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamService specParamService;

    public List<SpecGroupDTO> querySpecGroupByCid(Long id) {
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(id);
        List<SpecGroup> specGroups = specGroupMapper.select(specGroup);
        if(CollectionUtils.isEmpty(specGroups)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(specGroups,SpecGroupDTO.class);
    }

    public List<SpecGroupDTO> querySpecsByCid(Long id) {
        List<SpecGroupDTO> groupDTOS = querySpecGroupByCid(id);
        List<SpecParamDTO> params = specParamService.querySpecParam(null, id, null);
        Map<Long, List<SpecParamDTO>> map = params.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        for (SpecGroupDTO groupDTO : groupDTOS) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return groupDTOS;
    }
}
